package cn.net.lisong.blog.service.impl;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import cn.net.lisong.blog.dao.UserDAO;
import cn.net.lisong.blog.po.UserPO;
import cn.net.lisong.blog.service.UserService;

public class UserServiceImpl implements UserService {

	@Override
	public void save(UserPO user) {

		
		PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
		Properties properties = getPD();
		pooledDataSourceFactory.setProperties(properties);
		
		DataSource dataSource = pooledDataSourceFactory.getDataSource();
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		
		Environment environment = new Environment("development", transactionFactory, dataSource);
		
		Configuration configuration = new Configuration(environment);
		configuration.addMapper(UserDAO.class);
		 
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
		
		SqlSessionFactory factory = sqlSessionFactoryBuilder.build(configuration);
		
		SqlSession session = factory.openSession();
		try {
			UserDAO userDAO = session.getMapper(UserDAO.class);
			userDAO.save(user);
			session.commit();
			// do work
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unused")
	private Properties getPP() {
		
		Properties properties = new Properties();
		
		String host = System.getenv("MOPAAS_MYSQL15477_HOST");
		String port = System.getenv("MOPAAS_MYSQL15477_PORT");
		String db = System.getenv("MOPAAS_MYSQL15477_NAME");
		properties.setProperty("url",
		String.format("jdbc:mysql://%s:%s/%s", host, port, db));
		 
		String username = System.getenv("MOPAAS_MYSQL15477_USERNAME");
		String password = System.getenv("MOPAAS_MYSQL15477_PASSWORD");
		properties.setProperty("username", username);
		properties.setProperty("password", password);
		 
		String url = "org.mariadb.jdbc.Driver";
		properties.setProperty("url", url);
		
		return properties;
	}

	private Properties getPD() {
		
		Properties properties = new Properties();
		
		properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/myblog");
		 
		properties.setProperty("username", "blogger");
		properties.setProperty("password", "ma123456");
		
		String url = "org.mariadb.jdbc.Driver";
		properties.setProperty("driver", url);
		
		return properties;
	}

}
